#include "pch.h"
#include "WIC.h"
#include "Factories.h"
#include "IOHelper.h"

using namespace Platform;
using namespace DXBase;
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
using namespace concurrency;

ComPtr<IWICFormatConverter> WIC::LoadImage(Platform::String^ file)
{
	//return LoadImage(ctxt, ReadFile(file));
	// maybe not?
	//REMARK: DO not use the stream version, fails for ID2D1Image and .jpg

	auto pWFac = Factories::GetWicFactory();
	ComPtr<IWICBitmapDecoder> decoder;
	HR2Ex(pWFac->CreateDecoderFromFilename(IOHelper::FullPath(file)->Data(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnLoad, &decoder));

    ComPtr<IWICBitmapFrameDecode> frame;
    HR2Ex(decoder->GetFrame(0, &frame));

	ComPtr<IWICFormatConverter> pConv;
	HR2Ex(pWFac->CreateFormatConverter(&pConv));
	HR2Ex(pConv->Initialize(
		frame.Get(), 
		GUID_WICPixelFormat32bppPBGRA, 
		WICBitmapDitherTypeNone,
		nullptr,
		0.0,
		WICBitmapPaletteTypeMedianCut));//WICBitmapPaletteTypeCustom));

	return pConv;
}
ComPtr<IWICFormatConverter> WIC::LoadImage(const Platform::Array<byte>^ bytes)
{
	return LoadImage(IOHelper::Bytes2Stream(bytes));
}
ComPtr<IWICFormatConverter> WIC::LoadImage(Windows::Storage::Streams::IRandomAccessStream^ src)
{
    ComPtr<IStream> stream;
	HR2Ex(CreateStreamOverRandomAccessStream(src, IID_PPV_ARGS(&stream)));
	return LoadImage(stream);
}
ComPtr<IWICFormatConverter> WIC::LoadImage(ComPtr<IStream> stream)
{
	auto pWFac = Factories::GetWicFactory();
	
	ComPtr<IWICBitmapDecoder> decoder;
    HR2Ex(pWFac->CreateDecoderFromStream(stream.Get(), nullptr, WICDecodeMetadataCacheOnLoad, &decoder));

    ComPtr<IWICBitmapFrameDecode> frame;
    HR2Ex(decoder->GetFrame(0, &frame));

	ComPtr<IWICFormatConverter> pConv;
	HR2Ex(pWFac->CreateFormatConverter(&pConv));
	HR2Ex(pConv->Initialize(
		frame.Get(), 
		GUID_WICPixelFormat32bppPBGRA, 
		WICBitmapDitherTypeNone,
		nullptr,
		0.0,
		WICBitmapPaletteTypeMedianCut));//WICBitmapPaletteTypeCustom));

	//REMARK: DO NOT USE WITH ID2D1Image, .jpg, CreateBitmapFromWicBitmap
	return pConv;
}
